<template>
  <div class="net-info">
    <div class="base-area">
      <div class="title">基础信息</div>

      <el-form :model="baseForm" label-width="130px" ref="formRef" class="base-form" inline>
        <el-form-item label="品种代码" required prop="code">
          <el-input v-model="baseForm.code" @change="getPriceInfo" />
        </el-form-item>
        <el-form-item label="最新价格"> {{ stockInfo?.D.value || '-' }} </el-form-item>

        <el-form-item label="初始买入触发价" required prop="baseTrigger">
          <el-input v-model="baseForm.baseTrigger"></el-input>
        </el-form-item>
        <el-form-item label="初始买入金额">
          <el-input v-model="baseForm.baseCost"></el-input>
        </el-form-item>
        <el-form-item label="初始买入数量">
          {{ baseForm.baseNum }}
        </el-form-item>
        <el-form-item label="关联持仓">
          <el-select v-model="baseForm.holdId" @change="handleHoldChange">
            <el-option
              v-for="hold in innerHoldList || []"
              :key="hold.id"
              :value="hold.id"
              :label="`${hold.name}-${hold.strategyName}`"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="当前压力"> {{ baseForm.totalPressure }} </el-form-item>
        <el-form-item label="所有品种压力"> {{ allPressureInfo.total }} </el-form-item>
        <el-form-item label="压力剩余货币">
          <span :style="{ color: allPressureInfo.color }">{{ allPressureInfo.left }}</span>
        </el-form-item>

        <el-form-item class="btn-item">
          <div class="btn-area">
            <el-button @click="router.back()">取消</el-button>
            <el-button type="primary" @click="toSave">确认</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="net-area">
      <div class="title">网格信息</div>
      <div class="table-head table-row">
        <div class="buy-info">
          <span>档位</span><span>类型</span> <span>买触发价</span> <span>买入价</span>
          <span>应买数量</span>
          <span>应买金额</span>
        </div>
        <div class="sell-info">
          <span>卖出触发价</span> <span>卖出价</span> <span>应卖数量</span> <span>应卖金额</span>
          <span>盈利额</span> <span>盈利比</span>
        </div>
      </div>
      <div class="table-body">
        <NetRowVue
          ref="netRowRefs"
          v-for="index in netIndexList"
          :key="index + 'netRowRefs'"
          :index="index"
          :base-form="baseForm"
          :last-buy-trigger="lastBuyTrigger(index)"
          :last-ratio="lastRatio(index)"
          @add="handleAddNet"
          @delete="handleDeleteNet"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import NetRowVue from './NetRow.vue'
import { useRouter } from 'vue-router'

import { computed, nextTick, onMounted, ref } from 'vue'
import { usePressure } from './usePressure'
import { useAim } from '@/hooks/useAim'
import { useInnerStock } from '@/hooks/useInnerStock'
import { useInnerHold } from '@/hooks/useInnerHold'

import type { NetRow, NetItem, BaseForm } from './types'

const router = useRouter()
const { innerHoldList } = useInnerHold()
const { stockInfo, getPriceInfo } = useInnerStock()
const { totalPressure, updateTotalPressure, getPressureInfo } = usePressure()
const { isEdit } = useAim()
if (isEdit.value) {
  updateTotalPressure('id')
}

const allPressureInfo = computed(() => {
  const total = totalPressure.value + baseForm.value.totalPressure
  const { left, color } = getPressureInfo(total)
  return {
    total,
    left,
    color
  }
})

const baseForm = ref<BaseForm>({
  code: '',
  baseTrigger: 1,
  baseNum: 2000,
  baseCost: 2000,
  gap: 0.005,
  holdId: '',
  totalPressure: 0
})

const netIndexList = ref<number[]>([0])

const handleAddNet = (index: number) => {
  netIndexList.value.push(index + 1)
  nextTick(() => {
    baseForm.value.totalPressure = setTotalPressure()
  })
}

const handleDeleteNet = (index: number) => {
  netIndexList.value.splice(index, 1)
  nextTick(() => {
    baseForm.value.totalPressure = setTotalPressure()
  })
}

const netRowRefs = ref()

const lastBuyTrigger = computed(() => {
  return (index: number) => {
    if (!index) {
      return 0
    }
    return netRowRefs.value[index - 1].net.buyTrigger
  }
})

const lastRatio = computed(() => {
  return (index: number) => {
    if (!index) {
      return 1
    }
    return netRowRefs.value[index - 1].net.ratio as number
  }
})

const setTotalPressure = () => {
  const nowPrice = (stockInfo.value?.D.value || 0) as number
  return netRowRefs.value?.reduce((preTotal: number, curObj: { net: NetRow }) => {
    const { buyCost, buyPrice } = curObj.net
    if (nowPrice > buyPrice) {
      return +buyCost + preTotal
    } else {
      return preTotal
    }
  }, 0)
}

onMounted(() => {
  if (baseForm.value.code) {
    getPriceInfo(baseForm.value.code).then(() => {
      baseForm.value.totalPressure = setTotalPressure()
    })
  }
})

const formRef = ref()
const toSave = () => {
  formRef.value.validate((valid: boolean) => {
    if (!valid) {
      return
    }
    Promise.all(netRowRefs.value.map((net: { valid: () => Promise<boolean> }) => net.valid())).then(
      () => {
        const data: NetItem = {
          ...baseForm.value,
          netList: netRowRefs.value.map((netEl: { net: NetRow }) => netEl.net)
        }

        console.log(data, '--data')
      }
    )
  })
}

const handleHoldChange = () => {
  const { holdId } = baseForm.value
  const hold = innerHoldList.value.find((each) => each.id === holdId)
  baseForm.value.code = hold?.code || ''
  getPriceInfo(baseForm.value.code).then(() => {
    baseForm.value.totalPressure = setTotalPressure()
  })
}
</script>

<style lang="scss">
@import './style.scss';
.net-info {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 30px;
  box-sizing: border-box;
  .title {
    margin-bottom: 20px;
  }

  .el-input-number {
    max-width: 130px;
  }
}
.base-area {
  .base-form {
    display: grid;
    grid-template-columns: 1.6fr 1fr 1fr 1fr 1fr;
    justify-items: end;
    .btn-item {
      grid-column: 5;
      .btn-area {
        width: 100%;
        text-align: end;
      }
    }
  }

  border-bottom: 1px solid #e2e6ed;
}
.net-area {
  flex: 1;
  padding-top: 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
.table-body {
  flex: 1;
  overflow-y: auto;
  &:last-child {
    padding-bottom: 20px;
  }
}
</style>
../../hooks/useInnerHold
